<template>
  <Container class="dealer-sign-edit">
    <!-- 基础设置 -->
    <div class="container-header title title-center" slot="header">
      {{type!==0 ? '编辑' : '新增'}}签约经销商
      <Button
        size="large"
        class="fl btn-back"
        icon="ios-arrow-back"
        @click="$router.back()"
      >返回</Button>
    </div>
    <!-- 基本信息 -->
    <Tabs v-model="tab" @on-click="changeTab">
      <Button type="primary" size="large" slot="extra" class="mr" v-show="isAddSingn" @click="onClickEdit('', 0)">新增签约</Button>
      <TabPane name="tab1" label="基本信息" class="scroll">
        <BasicInfoItem ref="basicInfo"></BasicInfoItem>
      </TabPane>
      <TabPane name="tab2" label="签约信息"  class="scroll">
    <!-- 签约信息列表 -->
        <SubInfoItem ref="subInfo" v-show="!isEdit" @formDataByPhone='onformDataByPhone' @complete="onClickEdit"></SubInfoItem>
    <!-- 签约信息编辑状态 -->
        <DefaultEditItem ref="defaultForm" v-show="isEdit" :form="form" @formDataByPhone='onformDataByPhone' @changeBrand='onChangeBrand' :brandList='brandListWidthBind'></DefaultEditItem>
      </TabPane>
    </Tabs>
    <div class="container-footer bg-white" slot="footer" v-if="isEdit">
      <Button type="primary" size="large" class="ml" @click="jumpPrevPage">取消</Button>
      <Button type="primary" size="large" class="ml" @click="onsave">保存</Button>
    </div>
    <Loader :status="status" @refresh="getInfo"></Loader>
  </Container>
</template>
<script>
  import DefaultEditItem from "./edit/DefaultEditItem";
  import BasicInfoItem from "./edit/BasicInfoItem";
  import SubInfoItem from './edit/SubInfoItem'
  import { mapGetters } from 'vuex'
  import { getValueArray, setEmptyArray, setArrayValue} from '@/views/sales/common/TableSaleMethods'
  export default {
    name: "",
    components: {
      DefaultEditItem,
      BasicInfoItem,
      SubInfoItem
    },
    data() {
      return {
        loading: true,
        status: 'pass',
        id: '',
        tab: 'tab1',
        form: {
          id: '',
          distributorMobile: '', // 手机
          distributorSn: '', // 经销商编号
          isfg: true,
          isMessageNotification: false, // 短信通知开关
          distributorId: '',
          distributorContractName: '',
          distributorName: '', // 经销商签约名称
          distributorContact: '', // 经销商联系人
          provinceId: '',
          provinceName: '',
          cityId: '',
          cityName: '',
          areaId: '',
          areaName: '',
          address: '',
          bindBrandIds: '', // 经销商与改品牌商签约的所有品牌ids
          idCardNegativePic: '', // 法人身份证反面
          idCardPositivePic: '',
          businessLicensePic: '', // 营业执照
          areaDTOList: [], // 签约品牌业务区域list集合
          currentDistributorBrandDTO:{},
          // bindDepartmentId: '', // 签约经销商所属部门Id
          bindDepartmentName: '',
          domianPrefix: '',

          checkedIdList: [],
          cardz: [],
          cardf: [],
          yyzz: [],
        },
        brandDtos: [], //存储品牌签约状态
        isEdit: false, // 是否展示修改页面
        type: '' // 判断是新增还是修改 0 新增 1 修改
      }
    },
    created() {
      this.$store.dispatch('getBrandList', true)
      this.id = this.$route.query.id || ''
    },
    mounted() {},
    beforeDestroy() {
      // 清楚缓存
      this.$store.commit('setEmptyDealer')
    },
    methods: {
      // 切换tab
      changeTab() {},
      // 展示编辑页面
      onClickEdit(row, type) {
        this.type = type
        this.isEdit = true
        // 但是新增的情况从列表中取
        if (row.id) this.id = row.id
        if (this.id && this.type == 1) this.getInfo()
        if (this.id && this.type == 0) this.$refs.defaultForm.setList()
      },
      getInfo() {
        this.status = 'loading'
        this.$ajaxGet('/distributor/contract/findSignBrandById', { id: this.id}).then(res => {
          this.mergeData(res.distributorContractDTO)
          this.brandDtos = res.brandDtos
          this.status = 'pass'
        }).catch(err => {
          this.status = 'error'
        })
      },
      onformDataByPhone(val) {
        if (!val.distributorContractDTO) { // 未签约过
          const { name, sn, id,contactName, provinceId, provinceName, cityId, cityName, areaId, areaName,
         address, idCardNegativePic='', idCardPositivePic='', businessLicenseUrl='' } = val.distributorDTO;
          let obj = {distributorContractName: name, distributorName:name, distributorSn: sn, distributorId: id, distributorContact: contactName, provinceId, provinceName, cityId, cityName, areaId, areaName,
          address, idCardNegativePic, idCardPositivePic, businessLicensePic: businessLicenseUrl }
          this.form = Object.assign(this.form, obj)
          this.form.checkedIdList = (this.form.areaDTOList || []).map(item => item.areaId)
          this.form.cardz = idCardPositivePic ? [{status: 'finished', imgUrl: this.form.idCardPositivePic}] : []
          this.form.cardf = idCardNegativePic ? [{status: 'finished', imgUrl: this.form.idCardNegativePic}] : []
          this.form.yyzz = businessLicenseUrl ? [{status: 'finished', imgUrl: this.form.businessLicensePic}] : []
        } else {
          this.mergeData(val.distributorContractDTO)
          this.brandDtos = val.brandDtos
        }
        
      },
      onChangeBrand(item) {
        let brandId = item.brandId
        let distributorId = this.form.distributorId
        this.$ajaxGet('/distributor/contract/findByDistributorIdAndBrandId', { brandId, distributorId  }).then(res => {
          this.form.id = res ? res.id : ''
          this.mergeData(res)
        })
      },
      mergeData(newData) {
        if (!newData) return
        this.form = Object.assign(this.form, newData)
        this.form.areaDTOList = (newData.resultAreaDTOList || []).map(item => {
          return { areaId: item.areaId, areaName:item.areaName }
        })
        this.form.checkedIdList = (newData.resultAreaDTOList || []).map(item => item.areaId)
        const { currentBrandId, currentBrandName } = newData
        this.form.currentDistributorBrandDTO = { brandId: currentBrandId, brandName: currentBrandName }
        this.form.cardz = [{status: 'finished', imgUrl: this.form.idCardPositivePic}]
        this.form.cardf = [{status: 'finished', imgUrl: this.form.idCardNegativePic}]
        this.form.yyzz = [{status: 'finished', imgUrl: this.form.businessLicensePic}]
        if (this.form.cardz.length && !this.form.cardz[0].imgUrl) this.form.cardz = []
        if (this.form.cardf.length && !this.form.cardf[0].imgUrl) this.form.cardf = []
        if (this.form.yyzz.length && !this.form.yyzz[0].imgUrl) this.form.yyzz = []
      },
      jumpPrevPage() {
        this.isEdit = false
      },
      getTreeParams(data) {
        // 拿到树的数据和选中的比较 - 有的的化就把
        // checked = true isAllSelect = true 
        // indeterminate = false 删掉
        let data1 = JSON.parse(JSON.stringify(data))
        let loop = (data, val) => {
          for (let key in data) {
            if( !data[key][val.index] && !data[key].checked) {
                data[key] = ''
            }
            if (data[key].checked) {
              data[key].isAllSelect = true
            } else {
              if (data[key]) data[key].isAllSelect = false
            }
            if (data[key][val.childName] && data[key][val.childName].length) {
                loop(data[key][val.childName], val)
            }
          }
        }
        loop(data1, {index: 'indeterminate',childName: "children"})
        setEmptyArray(data1, {index: 'indeterminate',childName: "children"})
        this.form.areaDTOList = data1
      },
      getAreaList(data1) {
        let loop = (data) => {
          data.forEach((item, index) => {
            delete item.indeterminate
            if(item.children.length) {
              loop(item.children)
            }
          })
        }
        loop(data1)
      },
      onsave() {
        this.$refs["defaultForm"].$refs["form"].validate(valid => {
          if (valid) {
            this.$nextTick(()=> {
              let list = this.$refs.defaultForm.$refs.treeadd.$refs.tree.getCheckedAndIndeterminateNodes()
              if (list.length) {
                this.getTreeParams(list[0].children)
              }
            })
            if (this.status === 'loading') return
            this.status = 'loading'
            this.$jsonPost('/distributor/contract/saveSignBrand', this.form).then(res => {
              this.status = 'pass'
              this.$Message.success("保存成功!")
              this.$refs.subInfo.getData(this.form.distributorId)
              this.$refs.basicInfo.getData(this.form.distributorId)
              this.jumpPrevPage()
            }).catch(res => {
              this.status = 'pass'
            })
          }
        })
      }
    },
    computed: {
      ...mapGetters([
        'brandList'
      ]),
      brandListWidthBind() {
        return this.brandList.map(item => {
          if (this.brandDtos.find(i => i.brandName===item.brandName&&i.bind)) {
            item.bind = true
            item.disabled = true
          }
          if(this.type == 1) item.disabled = true
          return item
        })
      },
      isAddSingn() {
        return !this.isEdit && this.tab === 'tab2'
      }
    }
  };
</script>

